package com.cxgk.app.cxgkdemo.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.cxgk.app.cxgkdemo.R;
import com.cxgk.app.cxgkdemo.bean.Car;
import com.cxgk.app.cxgkdemo.logic.BaseModel;
import com.cxgk.app.cxgkdemo.utils.Constants;
import com.cxgk.app.cxgkdemo.utils.SweetAlertDialogFactory;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by lenovo on 2016/12/13.
 */

public class SearchResultActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_del, tv_carType, tv_buyTime, tv_carNumber, tv_commit;
    EditText et_carPrice;
    SimpleDraweeView iv_icon;
    File downLoadFile;
    Car mCar;
    DatePickerDialog mDatePickerDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        mLoadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                finish();
            }
        });
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.tv_commit).setOnClickListener(this);
        findViewById(R.id.ll_selectTime).setOnClickListener(this);
        tv_del = (TextView) findViewById(R.id.tv_del);
        tv_del.setOnClickListener(this);
        tv_commit = (TextView) findViewById(R.id.tv_commit);
        tv_commit.setOnClickListener(this);
        tv_carType = (TextView) findViewById(R.id.tv_carType);
        tv_carType.setText(getIntent().getExtras().getString(Constants.KEY_DEFAULE));
        tv_carNumber = (TextView) findViewById(R.id.tv_carNumber);
        tv_carNumber.setText(getIntent().getExtras().getString(Constants.KEY_OBJ1));
        et_carPrice = (EditText) findViewById(R.id.et_carPrice);
        tv_buyTime = (TextView) findViewById(R.id.tv_buyTime);
        iv_icon = (SimpleDraweeView) findViewById(R.id.iv_icon);
        iv_icon.setOnClickListener(this);
        initData();
        loadData();
    }

    /**
     * 初始化数据设置
     */
    private void initData() {
        Calendar calendar = Calendar.getInstance();
        mDatePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                tv_buyTime.setText(year + "-" + (month + 1) + "-" + day);
                mDatePickerDialog.dismiss();
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        mDatePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());

    }

    /**
     * 加载数据
     */
    private void loadData() {
        String carType = tv_carType.getText().toString();
        if (TextUtils.isEmpty(carType)) {
            SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("请选择车型").show();
            return;
        }
        String carNumber = tv_carNumber.getText().toString();
        if (TextUtils.isEmpty(carNumber)) {
            SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("请输入车号").show();
            return;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("CarType", carType);
            jsonObject.put("CarNum", carNumber);
            Call<BaseModel> call = mRestClient.getRectService().httpPost(Constants.DATA_TYPE_SEARCH, jsonObject.toString());
            mLoadingDialog.show();
            call.enqueue(new Callback<BaseModel>() {
                @Override
                public void onResponse(Call<BaseModel> call, Response<BaseModel> response) {
                    mLoadingDialog.dismiss();
                    if (response.body().success()) {
                        if (response.body().Items.size() > 0) {
                            tv_del.setVisibility(View.VISIBLE);//数据加载完成之后.在显示删除按钮

                            Gson gson = new Gson();
                            ArrayList<Car> cars = gson.fromJson(gson.toJson(response.body().Items), new TypeToken<ArrayList<Car>>() {
                            }.getType());
                            mCar = cars.get(0);
                            tv_carType.setText(mCar.getCarType());
                            tv_carNumber.setText(mCar.getCarNum());
                            et_carPrice.setText(mCar.getPrice() + "");
                            tv_buyTime.setText(mCar.getBuyTime());
                            String url = Constants.URL_DOMIAN + Constants.URL_MULTI + "?OperateType=2&FileType=2&FileName=" + mCar.getPictureName();
                            //                            mLoadingDialog.setContentText("正在下载图片");
                            mLoadingDialog.show();
                            downLoadImg(mCar.getPictureName());
                        } else {
                            SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("未查询到数据").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            }).show();
                        }
                    } else {
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(response.body().ResultText).show();
                    }
                }

                @Override
                public void onFailure(Call<BaseModel> call, Throwable t) {
                    t.printStackTrace();
                    mLoadingDialog.dismiss();
                    SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(getString(R.string.net_error_n)).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            finish();
                        }
                    }).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void downLoadImg(String fileName) {
        HashMap<String, String> queryMap = new HashMap<>();
        queryMap.put("OperateType", Constants.MULTI_OPERATE_TYPE_DOWN + "");
        queryMap.put("FileType", Constants.MULTI_TYPE_NORMAL + "");
        queryMap.put("FileName", fileName);
        Call<ResponseBody> call = mRestClient.getRectService().multiAction(queryMap);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    InputStream inputStream = response.body().byteStream();
                    if (inputStream.available() == 0) {
                        mLoadingDialog.dismiss();
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("没有图片").show();
                        return;
                    }
                    findViewById(R.id.tv_hit).setVisibility(View.VISIBLE);
                    downLoadFile = new File(Constants.DIR_IMAGES, getPhotoFileName());//保存图片路径
                    byte[] fileReader = new byte[2048];

                    OutputStream outputStream = new FileOutputStream(downLoadFile);
                    while (true) {
                        int read = inputStream.read(fileReader);
                        if (read == -1) {
                            break;
                        }
                        outputStream.write(fileReader, 0, read);
                    }
                    outputStream.flush();//保存图片
                    iv_icon.setImageURI(Uri.fromFile(downLoadFile)); //显示图片
                    tv_commit.setVisibility(View.VISIBLE);
                    mLoadingDialog.dismiss();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
                mLoadingDialog.dismiss();
                SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(getString(R.string.net_error_n)).show();

            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_icon:
                if (downLoadFile != null) {
                    Intent intent = new Intent(SearchResultActivity.this, DraweePhotoActivity.class);
                    intent.putExtra(Constants.KEY_DEFAULE, downLoadFile.getPath());
                    startActivity(intent);
                } else {
                    SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("没有图片").show();
                }
                break;
            case R.id.ll_selectTime:
                if (mDatePickerDialog.isShowing()) {
                    mDatePickerDialog.dismiss();
                } else {
                    mDatePickerDialog.show();
                }
                break;
            case R.id.tv_commit:
                updateCar();
                break;
            case R.id.tv_del:
                SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("确认删除数据").setCancelText("取消").setConfirmText("删除").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        del();
                    }
                }).show();
                break;
        }
    }

    private void updateCar() {

        String carPrice = et_carPrice.getText().toString();
        if (TextUtils.isEmpty(carPrice)) {
            SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("请输入购买价格").show();
            return;
        }
        String buyTime = tv_buyTime.getText().toString();
        if (TextUtils.isEmpty(buyTime)) {
            SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("请选择购买时间").show();
            return;
        }
        //上传
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("CarType", mCar.getCarType());
            jsonObject.put("CarNum", mCar.getCarNum());
            jsonObject.put("BuyTime", buyTime);
            jsonObject.put("Price", carPrice);
            jsonObject.put("PictureName", mCar.getPictureName());
            Call<BaseModel> call = mRestClient.getRectService().httpPost(Constants.DATA_TYPE_UDPATE, jsonObject.toString());
            mLoadingDialog.show();
            call.enqueue(new Callback<BaseModel>() {
                @Override
                public void onResponse(Call<BaseModel> call, Response<BaseModel> response) {
                    if (response.body().success()) {//基本参数提交之后上传图片
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.SUCCESS_TYPE, false).setContentText("修改成功").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                finish();
                            }
                        }).show();
                    } else {
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(response.body().ResultText).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        }).show();
                    }

                }

                @Override
                public void onFailure(Call<BaseModel> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除数据
     */
    private void del() {
        String carType = tv_carType.getText().toString();
        String carNumber = tv_carNumber.getText().toString();
        //上传
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("CarType", carType);
            jsonObject.put("CarNum", carNumber);
            Call<BaseModel> call = mRestClient.getRectService().httpPost(Constants.DATA_TYPE_DEL, jsonObject.toString());
            mLoadingDialog.show();
            call.enqueue(new Callback<BaseModel>() {
                @Override
                public void onResponse(Call<BaseModel> call, Response<BaseModel> response) {
                    mLoadingDialog.dismiss();
                    if (response.body().success()) {
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.SUCCESS_TYPE).setContentText("已删除").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                finish();
                            }
                        }).show();
                    } else {
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(response.body().ResultText).show();
                    }
                }

                @Override
                public void onFailure(Call<BaseModel> call, Throwable t) {
                    t.printStackTrace();
                    mLoadingDialog.dismiss();
                    SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(getString(R.string.net_error_n)).show();
                }

            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    // 获得照片的文件名称
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private Context getContext() {
        return this;
    }
}
